/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package taskgraph.tasks.data;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.EOFException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import taskgraph.ports.InputPort;
import taskgraph.ports.OutputPort;
import taskgraph.tasks.PrimitiveTask;


/**
 * Selects and outputs a specified field from object E. 
 * 
 * @author Armando Blancas
 * @see taskgraph.ports.InputPort
 * @see taskgraph.ports.OutputPort
 * @param <E> The type of elements from the input port.
 * @param <T> The type of fields values selected from E.
 */
public class Select<E, T> extends PrimitiveTask {

	private InputPort<E> input;
	private OutputPort<T> output;
	private String propertyName;
	
	/**
	 * This constructor allows creating instances as beans.
	 */
    public Select() {
    	// do nothing
    }

	/**
     * Select constructor.
     * 
     * @param input The input port.
     * @param output The output port.
     */
    public Select(final InputPort<E> input, 
    		      final OutputPort<T> output,
    		      String propertyName) {
    	setInput(input);
    	setOutput(output);
    	setPropertyName(propertyName);
    }

    /**
     * Gets the input port.
     * 
	 * @return The input port.
	 */
	public InputPort<E> getInput() {
		return input;
	}
	
    /**
     * Gets the output port.
     * 
	 * @return The output port.
	 */
	public OutputPort<T> getOutput() {
		return output;
	}

	/**
	 * Gets the name of the property to be selected.
	 * 
	 * @return The property {@code String} value.
	 */
	public String getPropertyName() {
		return propertyName;
	}

	/**
     * Performs the work of this task.
     * 
	 *<pre>
	 *while not EOF
	 *    read an object reference from input port
	 *    get the value of the selected property
	 *    write the value to the output port
	 *close input port
	 *close output port
	 *</pre>
	 */
	@SuppressWarnings("unchecked")
	@Override
    public void run() {
    	try {
    		// Read first here to obtain the getter method.
			E element = input.read();
    		Method readMethod = null;
			BeanInfo info = Introspector.getBeanInfo(element.getClass());
			for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
				if (pd.getName().equals(propertyName)) {
					readMethod = pd.getReadMethod();
				}
			}
			
    		while (!Thread.currentThread().isInterrupted()) {
    			/*
    			 * It's the client's responsibility that this cast will work.
    			 * The return type must be T as per the task declaration.
    			 */
    			T selection = (T) readMethod.invoke(element);
    			output.write(selection);
    			element = input.read();
            }
        } catch (InterruptedIOException e) {
        	// interruption request
		} catch (IntrospectionException e) {
            log.error("Select#run()", e);
		} catch (IllegalArgumentException e) {
            log.error("Select#run()", e);
		} catch (IllegalAccessException e) {
            log.error("Select#run()", e);
		} catch (InvocationTargetException e) {
            log.error("Select#run()", e);
        } catch (EOFException e) {
        	// we're done
        } catch (IOException e) {
        	// pipe synch error
            log.error("Select#run()", e);
		} finally {
			input.close();
			output.close();
        }
    }

	/**
	 * Sets the input port.
	 * 
	 * @param input The input port.
	 */
    public void setInput(final InputPort<E> input) {
    	if (input == null)
    		throw new IllegalArgumentException("input == null");
 		this.input = input;
	}

	/**
	 * Sets the output port.
	 * 
	 * @param output The output port.
	 */
    public void setOutput(final OutputPort<T> output) {
    	if (output == null)
    		throw new IllegalArgumentException("output == null");
 		this.output = output;
	}

	/**
	 * Sets the name of the property to be selected.
	 * 
	 * @param propertyName The {@code String} value to set.
	 */
	public void setPropertyName(final String propertyName) {
		if (propertyName == null) {
			throw new IllegalArgumentException("propertyName == null");
		}
		this.propertyName = propertyName;
	}

}
